from datetime import datetime, date
from flask import request, jsonify, current_app
from sqlalchemy import and_, or_, func, extract
from flasgger import swag_from
from app import db
from app.models.user import User
from app.models.venue import Venue, VenueTimeSlot
from app.models.order import Order
from app.api.v1 import api_v1
from app.utils.decorators import admin_required
from app.utils.response import success_response, error_response


@api_v1.route('/admin/orders/fixed-list', methods=['GET'])
@admin_required
@swag_from({
    "tags": ["订单管理"],
    "summary": "获取订单列表（修复版）",
    "description": "修复版订单列表接口，解决了时间字段序列化问题\n\n**🔐 需要管理员Token认证**\n\n**接口状态：已测试✅**",
    "security": [{"Bearer": []}],
    "parameters": [
        {
            "name": "page",
            "in": "query",
            "type": "integer",
            "default": 1,
            "description": "页码，从1开始"
        },
        {
            "name": "per_page",
            "in": "query",
            "type": "integer",
            "default": 10,
            "description": "每页数量，默认10条"
        },
        {
            "name": "search",
            "in": "query",
            "type": "string",
            "description": "搜索关键词（订单号）"
        },
        {
            "name": "status",
            "in": "query",
            "type": "integer",
            "enum": [0, 1, 2, 3, 4],
            "description": "订单状态筛选：0=待支付，1=已支付，2=已取消，3=已完成，4=已退款"
        },
        {
            "name": "venue_id",
            "in": "query",
            "type": "integer",
            "description": "场馆ID筛选"
        },
        {
            "name": "user_id",
            "in": "query",
            "type": "integer",
            "description": "用户ID筛选"
        },
        {
            "name": "start_date",
            "in": "query",
            "type": "string",
            "format": "date",
            "description": "开始日期筛选，格式：YYYY-MM-DD"
        },
        {
            "name": "end_date",
            "in": "query",
            "type": "string",
            "format": "date",
            "description": "结束日期筛选，格式：YYYY-MM-DD"
        }
    ],
    "responses": {
        "200": {
            "description": "获取成功",
            "schema": {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 200},
                    "message": {"type": "string", "example": "获取订单列表成功"},
                    "data": {
                        "type": "object",
                        "properties": {
                            "total": {"type": "integer", "description": "总记录数", "example": 183},
                            "pages": {"type": "integer", "description": "总页数", "example": 37},
                            "page": {"type": "integer", "description": "当前页码", "example": 1},
                            "per_page": {"type": "integer", "description": "每页数量", "example": 5},
                            "orders": {
                                "type": "array",
                                "description": "订单列表",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "id": {"type": "integer", "description": "订单ID", "example": 183},
                                        "order_no": {"type": "string", "description": "订单号", "example": "ORD20250113001"},
                                        "status": {"type": "integer", "description": "订单状态", "example": 1},
                                        "status_text": {"type": "string", "description": "状态描述", "example": "已支付"},
                                        "amount": {"type": "number", "description": "订单金额（元）", "example": 80.0},
                                        "created_at": {"type": "string", "description": "创建时间", "example": "2025-01-13 16:30:00"},
                                        "reservation_date": {"type": "string", "description": "预约日期", "example": "2025-01-15"},
                                        "time_slot": {"type": "string", "description": "时间段", "example": "18:00:00-20:00:00"},
                                        "user_id": {"type": "integer", "description": "用户ID", "example": 1},
                                        "venue_id": {"type": "integer", "description": "场馆ID", "example": 1},
                                        "venue_name": {"type": "string", "description": "场馆名称", "example": "篮球场A"},
                                        "user_name": {"type": "string", "description": "用户名称", "example": "张三"}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        "401": {
            "description": "未授权访问",
            "schema": {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 401},
                    "message": {"type": "string", "example": "请先登录"}
                }
            }
        }
    }
})
def get_orders_fixed_list():
    """获取订单列表（修复版本）"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status', type=int)
        venue_id = request.args.get('venue_id', type=int)
        user_id = request.args.get('user_id', type=int)
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        search = request.args.get('search', '').strip()
        
        # 使用原生SQL查询避免ORM时间字段问题
        where_conditions = []
        params = {}
        
        # 按状态筛选
        if status is not None:
            where_conditions.append("o.status = :status")
            params['status'] = status
            
        # 按场馆筛选
        if venue_id:
            where_conditions.append("o.venue_id = :venue_id")
            params['venue_id'] = venue_id
            
        # 按用户筛选
        if user_id:
            where_conditions.append("o.user_id = :user_id")
            params['user_id'] = user_id
            
        # 按日期范围筛选
        if start_date:
            try:
                datetime.strptime(start_date, '%Y-%m-%d')
                where_conditions.append("o.reservation_date >= :start_date")
                params['start_date'] = start_date
            except ValueError:
                pass
                
        if end_date:
            try:
                datetime.strptime(end_date, '%Y-%m-%d')
                where_conditions.append("o.reservation_date <= :end_date")
                params['end_date'] = end_date
            except ValueError:
                pass
        
        # 搜索功能（只按订单号搜索）
        if search:
            where_conditions.append("o.order_no LIKE :search")
            params['search'] = f'%{search}%'
        
        # 构建WHERE子句
        where_clause = " WHERE " + " AND ".join(where_conditions) if where_conditions else ""
        
        # 构建SQL查询
        count_sql = f"""
        SELECT COUNT(*) as total
        FROM orders o
        {where_clause}
        """
        
        # 计算偏移量
        offset = (page - 1) * per_page
        
        list_sql = f"""
        SELECT 
            o.id, o.order_no, o.status, o.amount,
            o.created_at, o.reservation_date, 
            o.start_time, o.end_time, o.user_id, o.venue_id,
            v.name as venue_name,
            u.nickname as user_name
        FROM orders o
        LEFT JOIN venues v ON o.venue_id = v.id
        LEFT JOIN users u ON o.user_id = u.id
        {where_clause}
        ORDER BY o.id DESC
        LIMIT :per_page OFFSET :offset
        """
        
        # 添加分页参数
        params['per_page'] = per_page
        params['offset'] = offset
        
        # 执行查询
        count_result = db.session.execute(db.text(count_sql), params)
        total = count_result.scalar()
        
        list_result = db.session.execute(db.text(list_sql), params)
        orders_data = []
        
        for row in list_result:
            orders_data.append({
                'id': row.id,
                'order_no': row.order_no,
                'user_id': row.user_id,
                'venue_id': row.venue_id,
                'status': row.status,
                'status_text': {0: '未支付', 1: '已支付', 2: '已取消', 3: '已完成', 4: '已退款'}.get(row.status, '未知'),
                'amount': float(row.amount) if row.amount else 0,
                'reservation_date': str(row.reservation_date) if row.reservation_date else None,
                'time_slot': f"{row.start_time}-{row.end_time}" if row.start_time and row.end_time else '未知时间',
                'venue_name': row.venue_name or '未知场馆',
                'user_name': row.user_name or '未知用户',
                'created_at': str(row.created_at) if row.created_at else None
            })
        
        # 计算总页数
        pages = (total + per_page - 1) // per_page
        
        return success_response({
            'total': total,
            'pages': pages,
            'page': page,
            'per_page': per_page,
            'orders': orders_data
        }, '获取订单列表成功')
        
    except Exception as e:
        current_app.logger.error(f"获取订单列表异常: {str(e)}")
        return error_response('服务器错误', 500) 